<template>
  <div>
    <div class="header-container">
      <div class="header-left">
        <el-input v-model="classname" placeholder="请输入班级名" clearable></el-input>
        <el-input v-model="titleh" placeholder="请输入标题" clearable></el-input>
        <div class="radio-group-container">
          <el-radio-group v-model="homeworkstatus" size="small" @change="search">
            <el-radio-button label="全部" value="0" />
            <el-radio-button label="未提交" value="1" />
            <el-radio-button label="已提交" value="2" />
            <el-radio-button label="已截止" value="3" />
          </el-radio-group>
        </div>
      </div >
      <div class="header-right"><el-button type="primary" @click="search" :loading="isLoading">搜索</el-button></div>
    </div>
    <div>

      <el-table
          :data="homeworkData"
          stripe
          border
          style="width: 100%"
          :row-style="tableRowClassName"
      >
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="作业标题" width="150" align="center"header-align="center"></el-table-column>
        <el-table-column prop="description" label="简述" width="150"align="center"header-align="center"></el-table-column>
        <el-table-column label="截止日期" width="250"align="center"header-align="center">
          <template #default="scope">
            <el-tooltip
                v-if="isDeadlinePassed(scope.row.deadline)"
                content="截止日期已过"
                placement="top"
            >
              <span style="color: gray">{{ scope.row.deadline }}</span>
            </el-tooltip>
            <span v-else>{{ scope.row.deadline }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="详细要求" width="100"align="center"header-align="center">
          <template #default="scope">
            <el-button type="primary" @click="downloadFile(scope.row.homeworkId)">下载</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="className" label="班级" width="160"align="center"header-align="center"></el-table-column>
        <el-table-column prop="teacherName" label="老师" width="100"align="center"header-align="center"></el-table-column>
        <el-table-column prop="contentS" label="内容" width="100"align="center"header-align="center">
          <template #default="scope">
            <el-button type="success" @click="dialogVisibleSubmit=true,homeworkId=scope.row.homeworkId" v-if="scope.row.contentS==null" :disabled="isDeadlinePassed(scope.row.deadline)">提交</el-button>
            <el-button type="primary" @click="downloadFile(scope.row.homeworkId)" v-if="scope.row.contentS!=null">下载</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" width="80"align="center"header-align="center"></el-table-column>
        <el-table-column prop="feedback" label="评语" width="200"align="center"header-align="center"></el-table-column>
        <el-table-column prop="submissionAt" label="提交时间" width="250"align="center"header-align="center"></el-table-column>
      </el-table>
    </div>
    <div class="flex-box">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 40, 50]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog
      v-model="dialogVisibleSubmit"
      title="编辑学生作业信息"
      width="500"
      :before-close="handleCloseSubmit"
  >
    <el-form :model="homeworkInfo" label-width="auto" style="max-width: 600px">
      <el-form-item
          label="作业文件"
          prop="content"
      >
        <el-upload
            class="upload-demo"
            drag
            action
            multiple
            :http-request="uploadfile"
            :data="file"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
            :limit="1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖至这里或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              文件大小不超过 5M，支持上传 PDF、Word、Excel 等文件
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button @click="dialogVisibleSubmit = false,homeworkInfo = {}">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {SearchStudent,AddSubmission} from '../../../api/homework.js'
import request from "../../../utils/request.js"
import {ElMessage} from "element-plus"

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const size = ref(false)
const disabled = ref(false)
const background = ref(false)
const homeworkData = ref([])
const isLoading = ref(false)
const dialogVisibleSubmit=ref(false)
const homeworkInfo=ref({
  content: null
})
const homeworkId=ref('')
const classname=ref('')
const titleh=ref('')
const homeworkstatus=ref('0')
const handleCloseSubmit = (done) => {
  homeworkInfo.value = {}
  dialogVisibleSubmit.value = false
  done()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  search()
}

const handleCurrentChange = () => {
  search()
}

const search = async () => {
  isLoading.value = true
  try {
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      const studentId = JSON.parse(userInfo).userId
      const res = await SearchStudent({
        pageno: currentPage.value,
        pagesize: pageSize.value,
        studentId: studentId,
        classname: classname.value,
        title: titleh.value,
        homeworkstatus: homeworkstatus.value
      })
      homeworkData.value = res.data.data.records
      total.value = res.data.data.total
    } else {
      console.error('用户信息不存在，请先登录！')
    }
  } catch (error) {
    console.error('搜索失败:', error)
  } finally {
    isLoading.value = false
  }
}
const downloadFile = async (id) => {
  try {
    const response = await request.get(`/homework/download/${id}`, {
      responseType: 'blob',
      params: { t: Date.now() } // 强制刷新
    });

    // 解析RFC 5987编码的文件名
    const contentDisposition = response.headers['content-disposition'];
    let fileName = 'file';
    if (contentDisposition) {
      const utf8FilenameRegex = /filename\*=UTF-8''([^;]+)/i;
      const matches = utf8FilenameRegex.exec(contentDisposition);
      fileName = matches ? decodeURIComponent(matches[1]) :
          contentDisposition.split('filename=')[1].replace(/["']/g, '');
    }

    // 创建Blob时指定MIME类型
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/octet-stream'
    });

    // 创建隐藏链接触发下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载失败:', error);
    // 显示错误提示
  }
}
const file = ref(null)

// 更健壮的上传处理方法
const uploadfile = (options) => {
  // 验证文件对象有效性
  if (options.file instanceof File) {
    file.value = options.file
    console.log('接收到的文件:', {
      name: options.file.name,
      size: options.file.size,
      type: options.file.type
    })
  } else {
    ElMessage.error('无效的文件对象')
    file.value = null
  }
}
const handleSuccess=(response, file, fileList)=> {
  console.log('上传成功:', response);
  // 根据响应处理逻辑
}
const handleError=(error, file, fileList)=> {
  console.error('上传失败:', error);
}
const beforeUpload=(file)=> {
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    this.$message.error('文件大小不能超过 5MB!');
  }
  return isLt5M;
}
const confirm = async () => {
  dialogVisibleSubmit.value = false

  // 校验必填字段
  if (!validateForm()) return

  // 构建 FormData（优化版）
  const formData = buildFormData()

  try {
    const apiMethod = AddSubmission
    await apiMethod(formData)

    ElMessage.success("提交成功")
    homeworkInfo.value = {}
    search()
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`)
  }
}
// 表单验证方法
const validateForm = () => {
  if (!file.value) {
    ElMessage.error('请上传文件')
    return false
  }


  return true
}
const buildFormData = () => {
  const formData = new FormData()
  // 文本字段（需处理空值情况）
  const fields = {
    homeworkId: homeworkId.value,
    studentId: JSON.parse(localStorage.getItem('userInfo')).userId
  }

  Object.entries(fields).forEach(([key, value]) => {
    if (value !== undefined) {
      formData.append(key, value)
    }
  })

  // 文件字段（强制校验）
  if (file.value instanceof File) {
    formData.append('content', file.value, file.value.name) // 第三个参数指定文件名
  }

  return formData
}
const isDeadlinePassed = (deadline) => {
  const now = new Date()
  const deadlineDate = new Date(deadline)
  return deadlineDate < now
}
// 动态设置行样式
const tableRowClassName = ({ row }) => {
  if (isDeadlinePassed(row.deadline)) {
    return 'expired-row'
  }
  return ''
}
onMounted(() => {
  search()
})
</script>

<style lang="less" scoped>
/* 行样式：灰色背景 */
.expired-row {
  background-color: red !important; /* 灰色背景 */
}
.radio-group-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  width: 100%; /* 宽度自适应 */
  max-width: 700px; /* 最大宽度限制 */
  margin: 0 auto; /* 居中对齐 */
  padding: 10px 0; /* 上下间距 */
}
.flex-box{
  display: flex;
  justify-content: center;
}
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  .header-left{
    display: flex;
    align-items: center;
    width: 65%;
  }
  .header-right{
    display: flex;
    justify-content: center;
    width: 35%;
  }
}
</style>
